package com.woniuxy.juc.aqs;

import com.woniuxy.untis.Sleep;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * <P> @Author: ideaAdmin
 * <P> TODO: Class
 * <P> TODO:
 * <P> Date: 2022/4/11:8:37
 * <P> Description:
 */
@Slf4j(topic = "c.c")
@SuppressWarnings("all")
public class AQSTest01 {
    public static void main(String[] args) {
        MyLock lock = new MyLock();
        new Thread(()->{
            lock.lock();
            log.debug("locking...");
            lock.lock();
            log.debug("locking...");
            try {
                log.debug("locking...");
                Sleep.sleep(2L);
            }finally {
                log.debug("unlocking...");
                lock.unlock();
            }
        },"t1").start();

        new Thread(()->{
            lock.lock();

            try {
                log.debug("locking...");
            }finally {
                log.debug("unlocking...");
                lock.unlock();
            }
        },"t2").start();
    }
}

/**
 * TODO:自定义锁（不可重入锁）
 **/
class MyLock implements Lock {

    /**
     * TODO: 独占锁 同步器类
     **/
    class MySync extends AbstractQueuedSynchronizer {
        /**
         * TODO:尝试加锁
         **/
        @Override
        protected boolean tryAcquire(int arg) {
            if (compareAndSetState(0, 1)) {
                //TODO 加上了锁 并设置 owner 为当前线程
                setExclusiveOwnerThread(Thread.currentThread());
                return true;
            }
            return false;
        }

        /**
         * TODO:释放锁
         **/
        @Override
        protected boolean tryRelease(int arg) {
            setExclusiveOwnerThread(null);
            setState(0);
            return true;
        }

        /**
         * TODO: 是否持有独占锁
         **/
        @Override
        protected boolean isHeldExclusively() {
            return getState() == 1;
        }

        public Condition newCondition() {
            return new ConditionObject();
        }
    }

    private MySync sync = new MySync();

    /**
     * TODO:加锁(不成功进入等待队列)
     **/
    @Override
    public void lock() {
        sync.acquire(1);
    }


    /**
     * TODO:加锁 可打断
     **/
    @Override
    public void lockInterruptibly() throws InterruptedException {
        sync.acquireInterruptibly(1);
    }


    /**
     * TODO: 尝试加锁(尝试一次)
     **/
    @Override
    public boolean tryLock() {
        return sync.tryRelease(1);
    }


    /**
     * TODO:尝试加锁 带超时机制
     **/
    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return sync.tryAcquireNanos(1, unit.toNanos(time));
    }

    /**
     * TODO 解锁
     */
    @Override
    public void unlock() {
        sync.release(1);
    }


    /**
     * TODO:创建条件变量
     **/
    @Override
    public Condition newCondition() {
        return sync.newCondition();
    }
}
